package org.robot.scm.platform;

import java.util.Objects;
import java.util.TimerTask;
import lombok.extern.slf4j.Slf4j;
import org.robot.scm.pojos.config.BaseConfig;
import org.robot.scm.pojos.BaseNotify;
import org.robot.scm.pojos.config.NightMode;

/**
 * @Author : Awn create on 2023/11/2 14:06
 */
@Slf4j
public class DefaultScheduler extends TimerTask {

    private final AbstractMonitor monitor;

    private BaseConfig config;

    private final ThreadLocal<BaseNotify> lastNotice = new ThreadLocal<>();

    public DefaultScheduler(AbstractMonitor monitor, BaseConfig config) {
        this.monitor = monitor;
        this.config = config;
    }

    public void refreshConfig(BaseConfig config) {
        this.config = config;
    }

    @Override
    public void run() {
        try {
            // 夜间模式且非例外不执行
            NightMode nightMode = config.get().getNightMode();
            if (nightMode.isNight(config) && nightMode.isInclude(config, monitor.getPlatform())) {
                return;
            }

            // 读取最新记录
            BaseNotify notice = monitor.doMonitor(config);
            if (Objects.isNull(notice)) {
                return;
            }

            // 首次启动是否通知
            if (!config.get().isStartNotify() && Objects.isNull(lastNotice.get())) {
                lastNotice.set(notice);
                return;
            }

            // 和上次通知一样无新告不通知
            if (Objects.nonNull(lastNotice.get()) && notice.equal(lastNotice.get())) {
                return;
            }

            // 有通知额外处理
            monitor.doAfter(config, notice);

            // 发送通知
            monitor.doSend(config, notice);

            // 记录上次的通知
            lastNotice.set(notice);
        } catch (Exception e) {
            log.warn("{} error", monitor.getPlatform().getVal(), e);
        }
    }
}
